<!--
  @Descripttion：楼层内容编辑
  @Author：zqy
  @Date：2022-12-14 13:06:26
  @Last Modified by：zqy
  @Last Modified time：2022-12-14 13:06:26
-->
<template>
  <el-dialog
    ref="formDlg"
    :title="`楼层内容${detail && detail.id?'编辑':'新增'}`"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clearForm"
    width="800px"
    @close="closeDialog"
  >
    <div style="padding-right:20px">
      <el-form ref="refForm" :rules="formRules" :model="formData" size="mini" label-width="90px">
        <el-form-item label="名称:" prop="name">
          <el-input v-model.trim="formData.name" placeholder="请输入名称" maxlength="10" show-word-limit />
        </el-form-item>
        <el-form-item label="封面图:">
          <div class="img-upload-container">
            <qup-img-uploader
              :width="100"
              :height="100"
              mask
              :image-url="cateImage.absoluteUrl"
              :relative-url="cateImage.relativeUrl"
              @upload-success="handleUploadSuccess"
              @remove="handleDelImg"
            />
            <div class="icon-msg">建议图片{{ imageSize?`尺寸大小 ${imageSize} ,`:'' }}{{ layoutData.imageOhterSize?`${layoutData.imageOhterSize},`:'' }}不超过1M,支持png\jpg\jpeg</div>
          </div>
        </el-form-item>
        <el-form-item v-if="ableConfigRole" label="角色权限:">
          <el-input v-model="formData.roleName" placeholder="请选择" @focus="handleOpenRole">
            <div slot="suffix">
              <i
                v-if="!!(formData.roleName)"
                class="el-input__icon el-icon-circle-close"
                @click.self="hanldeClearRole"
              />
              <i class="el-input__icon el-icon-search" @click.self="handleOpenRole" />
            </div>
          </el-input>
        </el-form-item>
        <el-form-item
          label="关联内容:"
          prop="gotoDTO"
          :rules="[
            { required:true, message: '请选择', trigger: 'change' }
          ]"
        >
          <RelateCategory
            ref="formLink"
            v-model="formData.gotoDTO"
          />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button v-loading="submiting" size="mini" type="primary" @click="submitForm">保存</el-button>
    </div>
    <RoleDlg
      v-if="showRoleDlg"
      multiple
      :visible.sync="showRoleDlg"
      :default-list="permissionRoles"
      @change="handleRoleChange"
    />
  </el-dialog>
</template>

<script>
import RelateCategory from '@/components/RelateCategoy'
import QupImgUploader from '@/components/imgUploader'
import RoleDlg from '@/components/RoleDlg/index'
import { saveFloorDetail } from '@/api/floorDetail'
export default {
  name: 'FloorItemEdit',
  components: { QupImgUploader, RelateCategory, RoleDlg },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detail: {
      type: [String, Object],
      default: ''
    },
    pageData: {
      type: Object,
      default: () => {}
    },
    layoutData: {
      type: [String, Object],
      default: ''
    }, // 所属楼层布局
    floorId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      submiting: false,
      formData: {
        name: '', // 楼层名称
        gotoDTO: {
          gotoType: '', // 关联类型
          categoryDTOList: [], // 类目ID
          filterId: '', // 商品中心类目模板
          gotoValue: '', // 关联内容值 (帮助中心详情ID，自定义页面ID，商品详情ID)
          gotoName: '' // 内容名称(帮助中心详情，自定义页面，商品详情)
        },
        pic: '',
        roleName: ''
      },
      formRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'change' }
        ]
      },
      cateImage: {
        absoluteUrl: '',
        relativeUrl: ''
      },
      permissionRoles: [],
      showRoleDlg: false
    }
  },

  computed: {
    imageSize() {
      if (this.layoutData && this.layoutData.imageWidth && this.layoutData.imageHeight) {
        return `${this.layoutData.imageWidth} * ${this.layoutData.imageHeight}`
      } else {
        return ''
      }
    },
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    ableConfigRole() {
      return [0, 1, 2, '0', '1', '2'].includes(this.pageData.id)
    }
  },
  created() {
    if (this.detail && this.detail.id) {
      this.initFormData(this.detail)
    }
  },

  methods: {
    closeDialog() {
      this.dialogShow = false
      this.clearForm()
    },
    clearForm(done) {
      this.formData = {
        name: '',
        pic: '',
        gotoDTO: {
          gotoType: '',
          categoryDTOList: [],
          filterId: '',
          gotoValue: '',
          gotoName: ''
        },
        roleName: ''
      }
      this.permissionRoles = []
      this.cateImage = {
        absoluteUrl: '',
        relativeUrl: ''
      }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    initFormData(data) {
      let roleName = ''
      if (this.ableConfigRole) {
        const roles = data.roles || []
        roleName = roles.map(v => v.roleName).join(',')
        this.permissionRoles = roles
      }
      this.formData = {
        name: data.name || '', // 楼层名称
        gotoDTO: {
          gotoType: data.gotoType || '',
          categoryDTOList: data.categoryDTOList || [],
          filterId: data.filterId || '',
          gotoValue: data.gotoValue || '',
          gotoName: data.gotoName || ''
        },
        pic: data.pic,
        roleName
      }
      if (data.pic) {
        this.cateImage = {
          absoluteUrl: this.formatImageUrl(data.pic),
          relativeUrl: data.pic
        }
      }
    },

    submitForm(type) {
      if (this.submiting) return
      this.$refs['refForm'].validate(async(valid) => {
        if (valid) {
          if (this.$refs.formLink) {
            const flag = this.$refs.formLink.validate()
            if (!flag) {
              this.$message.warning('关联内容不能为空')
              return false
            }
          }
          const { name, pic, gotoDTO } = this.formData
          const formData = { ...{ name, pic, floorConfId: this.floorId }, ...gotoDTO }
          let categoryDTOList = []
          if (gotoDTO && gotoDTO.categoryDTOList) {
            categoryDTOList = gotoDTO.categoryDTOList.map(v => {
              return {
                categoryId: v.categoryId,
                categoryName: v.categoryName
              }
            })
          }
          formData.categoryDTOList = categoryDTOList
          if (this.detail && this.detail.id) {
            formData.id = this.detail.id
          }
          if (this.ableConfigRole) {
            formData.roles = this.permissionRoles.map(v => {
              const obj = {
                roleName: v.roleName,
                roleCode: v.roleCode,
                roleId: v.roleId
              }
              if (formData.id) {
                obj.floorDetailId = formData.id
              }
              return obj
            })
          }

          this.submiting = true
          await saveFloorDetail(formData).then(res => {
            this.submiting = false
            if (res.success === 1) {
              this.$message.success(`${formData.id ? '编辑' : '新增'}保存成功`)
              this.$emit('success', !!formData.id)
              this.closeDialog()
            }
          }).catch(() => {
            this.submiting = false
          })
        }
      })
    },
    handleUploadSuccess(res, file, fileList) {
      this.formData.pic = res.storeFileName
      this.cateImage = {
        absoluteUrl: res.url,
        relativeUrl: res.storeFileName
      }
    },
    handleDelImg() {
      this.formData.pic = ''
      this.cateImage = {
        absoluteUrl: '',
        relativeUrl: ''
      }
    },
    // 清空角色
    hanldeClearRole() {
      this.permissionRoles = []
      this.$set(this.formData, 'roleName', '')
    },
    // 打开角色选择
    handleOpenRole() {
      this.showRoleDlg = true
    },
    handleRoleChange(data) {
      const list = data || []
      const names = list.map(v => v.roleName)
      this.$set(this.formData, 'roleName', names.join(','))
      this.permissionRoles = list
    }

  }
}
</script>
<style lang='scss' scoped>
  .floor-layout{
    width: fit-content;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-end;
    .alert-msg{
      margin-left: 10px;
      color: #999;
    }
  }
  .img-upload-container {
    .icon-msg{
      margin-top: 10px;
      color: #999;
    }
  }
</style>
